package cn.edu.buu.hospital.web;
import cn.edu.buu.hospital.entity.Department;
import cn.edu.buu.hospital.service.DepartmentService;
import cn.edu.buu.hospital.service.HospitalService;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import jakarta.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/department")
public class DepartmentController {

    @Autowired
    private DepartmentService departmentService;
    
    @Autowired
    private HospitalService hospitalService;

    // 跳转到新增科室页面
    @GetMapping("/toAdd")
    public String toAdd(Model model, HttpSession session) {
        // 添加医院列表到model中
        model.addAttribute("hospitalList", hospitalService.findAll());
        
        // 从session中获取临时保存的科室数据
        Department addDepartment = (Department) session.getAttribute("addDepartment");
        if (addDepartment != null) {
            model.addAttribute("addDepartment", addDepartment);
            // 移除session中的临时数据，避免重复使用
            session.removeAttribute("addDepartment");
        }
        
        return "backend/department/add";
    }

    // 新增科室
    @PostMapping("/add")
    public String add(Department department, Model model, HttpSession session) {
        try {
            departmentService.add(department);
            // 新增成功后，移除可能存在的临时数据
            session.removeAttribute("addDepartment");
            // 添加成功消息
            session.setAttribute("successMessage", "科室添加成功！");
            return "redirect:find";
        } catch (RuntimeException e) {
            // 保存用户输入到session，以便在重定向后恢复
            session.setAttribute("addDepartment", department);
            model.addAttribute("errorMessage", e.getMessage());
            model.addAttribute("hospitalList", hospitalService.findAll());
            return "backend/department/add";
        } catch (Exception e) {
            // 保存用户输入到session，以便在重定向后恢复
            session.setAttribute("addDepartment", department);
            model.addAttribute("errorMessage", "新增失败: " + e.getMessage());
            model.addAttribute("hospitalList", hospitalService.findAll());
            return "backend/department/add";
        }
    }

    // 查询科室列表
    @RequestMapping(value = "/find", method = {RequestMethod.GET, RequestMethod.POST})
    public String find(Model model,
                      @RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
                      Department condition,
                      HttpSession session) {
        // 从session获取并移除消息
        String successMessage = (String) session.getAttribute("successMessage");
        if (successMessage != null) {
            model.addAttribute("successMessage", successMessage);
            session.removeAttribute("successMessage");
        }
        
        String errorMessage = (String) session.getAttribute("errorMessage");
        if (errorMessage != null) {
            model.addAttribute("errorMessage", errorMessage);
            session.removeAttribute("errorMessage");
        }
        
        int pageSize = 5;

        PageInfo<Department> pageInfo = departmentService.find(pageNum, pageSize, condition);
        long totalDepartments = departmentService.findTotal();
        model.addAttribute("pageInfo", pageInfo);
        model.addAttribute("condition", condition);
        model.addAttribute("totalDepartments", totalDepartments);
        model.addAttribute("hospitalList", hospitalService.findAll());
        return "backend/department/list";
    }

    // 根据ID查询科室（用于编辑）
    @GetMapping("/findById")
    public String findById(@RequestParam("deptId") Long deptId, Model model, HttpSession session) {
        // 从session中获取临时保存的科室数据
        Department modifyDepartment = (Department) session.getAttribute("modifyDepartment");
        
        if (modifyDepartment != null && modifyDepartment.getDeptid().equals(deptId)) {
            // 如果有临时数据且ID匹配，则使用临时数据
            model.addAttribute("department", modifyDepartment);
            // 移除session中的临时数据
            session.removeAttribute("modifyDepartment");
        } else {
            // 否则根据ID查询科室信息
            Department department = departmentService.findById(deptId);
            if (department == null) {
                department = new Department();
                department.setDeptid(deptId);
            }
            model.addAttribute("department", department);
        }
        
        // 查询所有医院并添加到model中
        model.addAttribute("hospitalList", hospitalService.findAll());
        
        return "backend/department/edit";
    }

    // 修改科室信息
    @PostMapping("/modify")
    public String modify(Department department, Model model, HttpSession session) {
        try {
            departmentService.modify(department);
            // 修改成功后，移除可能存在的临时数据
            session.removeAttribute("modifyDepartment");
            // 添加成功消息
            session.setAttribute("successMessage", "科室修改成功！");
            return "redirect:find";
        } catch (RuntimeException e) {
            // 保存用户输入到session，以便在重定向后恢复
            session.setAttribute("modifyDepartment", department);
            model.addAttribute("errorMessage", e.getMessage());
            model.addAttribute("hospitalList", hospitalService.findAll());
            return "backend/department/edit";
        } catch (Exception e) {
            // 保存用户输入到session，以便在重定向后恢复
            session.setAttribute("modifyDepartment", department);
            model.addAttribute("errorMessage", "修改失败: " + e.getMessage());
            model.addAttribute("hospitalList", hospitalService.findAll());
            return "backend/department/edit";
        }
    }

    // 删除科室
    @GetMapping("/removeById")
    // 注意：Controller层不需要添加@Transactional注解，事务应该在Service层控制
    public String removeById(@RequestParam("deptId") Long deptId, HttpSession session) {
        System.out.println("接收到科室删除请求，科室ID: " + deptId);
        try {
            departmentService.removeById(deptId);
            // 设置成功消息
            session.setAttribute("successMessage", "科室删除成功！");
            System.out.println("科室删除成功，科室ID: " + deptId);
        } catch (RuntimeException e) {
            // 使用异常中提供的具体错误消息
            String errorMsg = "删除失败：" + e.getMessage();
            System.out.println(errorMsg); // 打印错误信息到控制台，方便调试
            session.setAttribute("errorMessage", errorMsg);
        } catch (Exception e) {
            // 处理其他未预期的异常
            String errorMsg = "删除失败：系统错误，请稍后重试";
            System.out.println(errorMsg + ": " + e.getMessage()); // 打印错误信息到控制台，方便调试
            e.printStackTrace();
            session.setAttribute("errorMessage", errorMsg);
        }
        return "redirect:find";
    }
    // 获取所有科室数据（用于科室名称下拉列表）
    @GetMapping("/getAllDepartments")
    @ResponseBody
    public List<Department> getAllDepartments() {
        try {
            System.out.println("开始获取所有科室数据...");
            List<Department> departments = departmentService.findAll();
            System.out.println("获取到科室数量: " + (departments != null ? departments.size() : 0));
            return departments;
        } catch (Exception e) {
            System.err.println("获取科室数据时发生错误: " + e.getMessage());
            e.printStackTrace();
            return new ArrayList<>();
        }
    }
}